'use client';

import React, { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import AppHeader from '@/components/ui/app-header';
import { UserProfile, UserStats } from '@/types/user';
import { Tab } from '@headlessui/react';
import {
  UserIcon,
  ChatBubbleLeftEllipsisIcon,
  FolderIcon,
  ChartPieIcon,
  PencilIcon,
} from '@heroicons/react/24/outline';
import ProfileDialog from '@/components/ui/profile-dialog';
import { useUserStore } from '@/store/user-store';

export default function ProfilePage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [showProfileDialog, setShowProfileDialog] = useState(false);
  
  // 从用户Store获取状态和方法
  const { 
    userData,
    profile, 
    isLoading, 
    error, 
    fetchUserData, 
    updateUserProfile 
  } = useUserStore();
  
  // 如果未登录，重定向到登录页
  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/login');
    }
  }, [status, router]);
  
  // 加载用户资料
  useEffect(() => {
    if (status === 'authenticated') {
      fetchUserData().catch(err => {
        console.error('获取用户数据失败:', err);
      });
    }
  }, [status, fetchUserData]);
  
  // 处理保存个人资料
  const handleSaveProfile = async (updatedProfile: UserProfile) => {
    try {
      // 调用Store方法更新资料
      await updateUserProfile(updatedProfile);
      return Promise.resolve();
    } catch (err) {
      console.error('更新个人资料失败:', err);
      return Promise.reject(err);
    }
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="min-h-screen bg-gray-100">
        <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
          <AppHeader
            title="个人资料"
            subtitle="查看和管理你的个人信息和活动统计"
            actions={
              <button
                type="button"
                disabled
                className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
              >
                <PencilIcon className="h-4 w-4 mr-1" />
                编辑资料
              </button>
            }
          />
          <div className="flex justify-center mt-10">
            <div className="animate-pulse flex space-x-4 w-full max-w-3xl">
              <div className="rounded-full bg-gray-200 h-20 w-20"></div>
              <div className="flex-1 space-y-6 py-1">
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                <div className="space-y-3">
                  <div className="h-3 bg-gray-200 rounded w-5/6"></div>
                  <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                </div>
              </div>
            </div>
          </div>
        </main>
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="min-h-screen bg-gray-100">
        <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
          <AppHeader
            title="个人资料"
            subtitle="查看和管理你的个人信息和活动统计"
          />
          <div className="mt-6 bg-white shadow overflow-hidden sm:rounded-lg p-6">
            <div className="p-4 border-l-4 border-red-500 bg-red-50 text-red-700">
              <p>{error}</p>
              <button
                onClick={() => fetchUserData()}
                className="mt-2 text-sm font-medium text-red-700 hover:text-red-600 underline"
              >
                重试
              </button>
            </div>
          </div>
        </main>
      </div>
    );
  }
  
  console.log("userData:", userData);
  console.log("profile:", profile);

  // 调整判断逻辑，确保在有数据时渲染
  if (!userData || !userData.profile) {
    return (
      <div className="min-h-screen bg-gray-100">
        <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
          <AppHeader
            title="个人资料"
            subtitle="查看和管理你的个人信息和活动统计"
          />
          <div className="mt-6 bg-white shadow overflow-hidden sm:rounded-lg p-6">
            <div className="p-4 border-l-4 border-yellow-500 bg-yellow-50 text-yellow-700">
              <p>未找到用户资料信息</p>
              <button
                onClick={() => fetchUserData()}
                className="mt-2 text-sm font-medium text-yellow-700 hover:text-yellow-600 underline"
              >
                刷新
              </button>
            </div>
          </div>
        </main>
      </div>
    );
  }
  
  // 使用 userData 中的 profile，不再使用 store 中的 profile
  const userProfile = userData.profile;
  // 提取统计数据
  const stats = userData.stats || {};
  
  return (
    <div className="min-h-screen bg-gray-100">
      <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <AppHeader
          title="个人资料"
          subtitle="查看和管理你的个人信息和活动统计"
          actions={
            <button
              type="button"
              onClick={() => setShowProfileDialog(true)}
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              <PencilIcon className="h-4 w-4 mr-1" />
              编辑资料
            </button>
          }
        />
        
        <div className="mt-6">
          {/* 个人资料卡片 */}
          <div className="bg-white shadow overflow-hidden sm:rounded-lg">
            <div className="px-4 py-5 sm:p-6">
              <div className="flex items-center">
                <div className="flex-shrink-0 h-20 w-20 relative">
                  {userProfile.image ? (
                    <Image
                      src={userProfile.image}
                      alt={userProfile.name}
                      fill
                      className="rounded-full object-cover border-2 border-blue-100"
                    />
                  ) : (
                    <div className="h-full w-full rounded-full bg-blue-100 flex items-center justify-center">
                      <UserIcon className="h-10 w-10 text-blue-500" aria-hidden="true" />
                    </div>
                  )}
                </div>
                <div className="ml-6 flex-1">
                  <div className="flex justify-between items-start">
                    <div>
                      <h3 className="text-2xl font-bold text-gray-900">{userProfile.name}</h3>
                      <p className="text-sm text-gray-500">{userProfile.jobTitle || '未设置职位'}</p>
                      <p className="text-sm text-gray-500">{userProfile.location || '未设置位置'}</p>
                      <p className="mt-1 text-sm text-gray-500">
                        加入时间: {userProfile.joinedAt ? new Date(userProfile.joinedAt).toLocaleDateString('zh-CN') : '未知'}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              
              <div className="mt-6">
                <h4 className="text-lg font-medium text-gray-900">关于</h4>
                <p className="mt-1 text-sm text-gray-600">{userProfile.bio || '暂无介绍'}</p>
              </div>
              
              {userProfile.skills && userProfile.skills.length > 0 && (
                <div className="mt-6">
                  <h4 className="text-lg font-medium text-gray-900">技能</h4>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {userProfile.skills.map((skill, index) => (
                      <span
                        key={index}
                        className="inline-flex items-center px-2.5 py-0.5 rounded-md text-sm font-medium bg-blue-100 text-blue-800"
                      >
                        {skill}
                      </span>
                    ))}
                  </div>
                </div>
              )}
              
              {userProfile.socialLinks && Object.values(userProfile.socialLinks).some(link => !!link) && (
                <div className="mt-6">
                  <h4 className="text-lg font-medium text-gray-900">社交链接</h4>
                  <div className="mt-2 flex space-x-4">
                    {userProfile.socialLinks.github && (
                      <a
                        href={userProfile.socialLinks.github}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-gray-500 hover:text-gray-900 flex items-center"
                      >
                        <svg className="h-5 w-5 mr-1" fill="currentColor" viewBox="0 0 24 24">
                          <path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
                        </svg>
                        GitHub
                      </a>
                    )}
                    {userProfile.socialLinks.linkedin && (
                      <a
                        href={userProfile.socialLinks.linkedin}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-gray-500 hover:text-gray-900 flex items-center"
                      >
                        <svg className="h-5 w-5 mr-1" fill="currentColor" viewBox="0 0 24 24">
                          <path d="M19 0h-14c-2.761 0-5 2.239-5 5v14c0 2.761 2.239 5 5 5h14c2.762 0 5-2.239 5-5v-14c0-2.761-2.238-5-5-5zm-11 19h-3v-11h3v11zm-1.5-12.268c-.966 0-1.75-.79-1.75-1.764s.784-1.764 1.75-1.764 1.75.79 1.75 1.764-.783 1.764-1.75 1.764zm13.5 12.268h-3v-5.604c0-3.368-4-3.113-4 0v5.604h-3v-11h3v1.765c1.396-2.586 7-2.777 7 2.476v6.759z"/>
                        </svg>
                        LinkedIn
                      </a>
                    )}
                    {userProfile.socialLinks.twitter && (
                      <a
                        href={userProfile.socialLinks.twitter}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-gray-500 hover:text-gray-900 flex items-center"
                      >
                        <svg className="h-5 w-5 mr-1" fill="currentColor" viewBox="0 0 24 24">
                          <path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/>
                        </svg>
                        Twitter
                      </a>
                    )}
                    {userProfile.socialLinks.website && (
                      <a
                        href={userProfile.socialLinks.website}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-gray-500 hover:text-gray-900 flex items-center"
                      >
                        <svg className="h-5 w-5 mr-1" fill="currentColor" viewBox="0 0 24 24">
                          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>
                        </svg>
                        网站
                      </a>
                    )}
                  </div>
                </div>
              )}
            </div>
            
            {/* 统计信息卡片 */}
            <div className="border-t border-gray-200 px-4 py-5 sm:p-6">
              <h3 className="text-lg font-medium leading-6 text-gray-900">统计信息</h3>
              <div className="mt-5 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
                <div className="overflow-hidden rounded-lg bg-white px-4 py-5 shadow">
                  <dt className="truncate text-sm font-medium text-gray-500">项目数</dt>
                  <dd className="mt-1 text-3xl font-semibold tracking-tight text-blue-600">{stats.projectCount || 0}</dd>
                </div>
                <div className="overflow-hidden rounded-lg bg-white px-4 py-5 shadow">
                  <dt className="truncate text-sm font-medium text-gray-500">任务总数</dt>
                  <dd className="mt-1 text-3xl font-semibold tracking-tight text-blue-600">{stats.tasks?.total || 0}</dd>
                </div>
                <div className="overflow-hidden rounded-lg bg-white px-4 py-5 shadow">
                  <dt className="truncate text-sm font-medium text-gray-500">已完成任务</dt>
                  <dd className="mt-1 text-3xl font-semibold tracking-tight text-green-600">{stats.tasks?.completed || 0}</dd>
                </div>
                <div className="overflow-hidden rounded-lg bg-white px-4 py-5 shadow">
                  <dt className="truncate text-sm font-medium text-gray-500">进行中任务</dt>
                  <dd className="mt-1 text-3xl font-semibold tracking-tight text-yellow-600">{stats.tasks?.inProgress || 0}</dd>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        {/* 最近活动卡片 */}
        {userData.recentActivities && userData.recentActivities.length > 0 && (
          <div className="mt-6 bg-white shadow overflow-hidden sm:rounded-lg">
            <div className="px-4 py-5 sm:px-6">
              <h3 className="text-lg leading-6 font-medium text-gray-900">最近活动</h3>
            </div>
            <div className="border-t border-gray-200">
              <ul className="divide-y divide-gray-200">
                {userData.recentActivities.map((activity: any) => (
                  <li key={activity.id} className="px-4 py-4 sm:px-6">
                    <div className="flex items-center">
                      <div className="min-w-0 flex-1">
                        <p className="text-sm font-medium text-gray-900 truncate">
                          {activity.description || activity.type}
                        </p>
                        <p className="text-sm text-gray-500">
                          {new Date(activity.createdAt).toLocaleString('zh-CN')}
                        </p>
                      </div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        )}
        
        {/* 编辑个人资料对话框 */}
        {showProfileDialog && userProfile && (
          <ProfileDialog
            open={showProfileDialog}
            setOpen={setShowProfileDialog}
            profile={userProfile}
            onSave={handleSaveProfile}
          />
        )}
      </main>
    </div>
  );
} 